import CoreBluetooth
import FastSwiftSDK

class XXBTManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
    public static var shared = XXBTManager()
    var connectState = 0
    var centralManager: CBCentralManager!
    var discoveredPeripheral: CBPeripheral?
    var characteristic: CBCharacteristic!
    var stateBlock:FastIntBlock?
 
    override init() {
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    // MARK: - CBCentralManagerDelegate Methods
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            // 开始扫描设备
            centralManager.scanForPeripherals(withServices: nil, options: nil)
        } else {
            print("Bluetooth is not available.")
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("Discovered \(peripheral.name ?? "Unknown")")
        let name = peripheral.name
        if name == "ESP32"{
            discoveredPeripheral = peripheral
            centralManager.stopScan() // 停止扫描
            centralManager.connect(peripheral, options: nil) // 链接
        }
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Connected to \(peripheral.name ?? "Unknown")")
        peripheral.delegate = self
        connectState = 1
        self.stateBlock?(connectState)
        peripheral.discoverServices(nil)
    }
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        connectState = 0
        self.stateBlock?(connectState)
        // 开始扫描设备
        centralManager.scanForPeripherals(withServices: nil, options: nil)
    }
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, timestamp: CFAbsoluteTime, isReconnecting: Bool, error: Error?) {
        connectState = 0
        self.stateBlock?(connectState)
        // 开始扫描设备
        centralManager.scanForPeripherals(withServices: nil, options: nil)
    }
    
    // MARK: - CBPeripheralDelegate Methods
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        for service in peripheral.services ?? [] {
            peripheral.discoverCharacteristics(nil, for: service)
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
            for characteristic in service.characteristics! {
                self.characteristic = characteristic
                // 发送数据
                sendData(data: "Hello World")
            }
        }

        func sendData(data: String) {
            if let dataToSend = data.data(using: .utf8) {
                discoveredPeripheral?.writeValue(dataToSend, for: characteristic, type: .withResponse)
                print("发送数据: \(data)")
            }
        }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        if let data = characteristic.value {
            // 处理接收到的数据
            print("Received data: \(data)")
        }
    }
}

